<template>
	<view class="chatInterface" >
		<!-- <image class="group-icon" src="/static/images/group-icon.png" @click="showMembers" /> -->
		<view class="scroll-view">
			<view class="all-history-loaded">
				{{allHistoryLoaded ? '已经没有更多的历史消息' : '下拉获取历史消息'}}
			</view>
			<checkbox-group @change="selectMessages">
				<view v-for="(message,index) in messages" :key="message.messageId">
					<!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
					<view class="time-lag">
						{{renderMessageDate(message, index)}}
					</view>
					<view class="message-recalled" v-if="message.recalled">
						<view v-if="message.senderId !== currentUser.id">{{message.senderData.name}}撤回了一条消息</view>
						<view v-else class="message-recalled-self">
							<view>你撤回了一条消息</view>
							<span v-if="message.type === 'text' && Date.now()-message.timestamp< 60 * 1000 " @click="editRecalledMessage(message.payload.text)">重新编辑</span>
						</view>
					</view>
					<view class = "message-item" v-else>
						<view class="message-item-checkbox">
							<checkbox v-show="messageSelector.visible && message.status !== 'sending'" :value="message.messageId" :checked="messageSelector.messages.includes(message)" />
						</view>
                        
						<view class="message-item-content" :class="{'self' : message.senderId ===  currentUser.id}">
							<view class="avatar">
								<image style="border-radius: 10rpx;" @click="leftAvatarClick(message.senderId)" :src="message.senderData.avatar"></image>
							</view>
							<view class="content" @longpress="showActionPopup(message)">
								<view class="message-payload">
									<b class="pending" v-if="message.status === 'sending'"></b>
									<b class="send-fail" v-if="message.status === 'fail'"></b>
                                    <view class="text-content" v-if="message.status ==='addUser'">{{message.payload}}</view>
									<view v-if="message.type === 'text'" class="text-content">{{message.payload.text}}</view>
									<image class="image-content" v-if="message.type === 'image'" :src="message.payload.url" :data-url="message.payload.url" @click="showImageFullScreen" mode="widthFix"></image>
									<view class="video-snapshot"  v-if="message.type === 'video'" :data-url="message.payload.video.url" @click="playVideo">
										<image :src="message.payload.thumbnail.url" mode="aspectFit"></image>
										<view class="video-play-icon"></view>
									</view>
							        <image class="image-content" v-if="message.type === 'emoji'" :src="message.payload"></image>
							        <!-- 视频 -->
									<GoEasyAudioPlayer v-if="message.type ==='audio'" :src="message.payload.url" :duration="message.payload.duration" />
							        <!-- 红包 -->
							        <view v-if="message.type=='redpacket' " @tap='redpack_open(message)'
							        	:class="{'redpack':true,'redpack-open':message.payload.content.isopen==1}"
							        	@longtap="msgAction($event,message)">
							        	<view class="info">
							        		<block v-if="message.senderId==currentUser.id">
							        			<view class="icon">
							        				<image
							        					:src="message.payload.content.isopen==1?'/static/img/redpackopen-icon.png':'/static/img/redpack-icon.png'">
							        				</image>
							        			</view>
							        			<view class="showtext">{{message.payload.content.title}}</view>
							        
							        		</block>
							        
							        		<block v-else>
							        			<view class="icon">
							        				<image
							        					:src="message.payload.content.isopen==1?'/static/img/redpackopen-icon.png':'/static/img/redpack-icon.png'">
							        				</image>
							        			</view>
							        			<view class="showtext">{{message.payload.content.title}}</view>
							        		</block>
							        
							        	</view>
							        	<view class="title" style="text-align: right;padding-right: 20rpx;">{{isType[message.payload.content.type]}}</view>
							        </view>
								</view>
								<view v-if="message.senderId === currentUser.id&&message.type!='redpacket'" :class="message.read ?'message-read':'message-unread'">
									<view v-if="message.status === 'success'">{{message.read?'已读':'未读'}}</view>
								</view>
							</view>
						</view>
                        
					</view>
				</view>
			</checkbox-group>
		</view>
		<view class="action-box" style="z-index: 99999 !important;" v-if="!videoPlayer.visible && !messageSelector.visible">
			<view class="action-top" style="display: flex;align-items: center;justify-content: space-between;">
                <view class="emoji" style="width: 12%;text-align: center;"  @click="switchAudioKeyboard">
                    <text style="font-size: 31px;"  :class="[audio.visible ? 'n-icon n-icon-keyboard':'n-icon n-icon-voice']" class="n-icon n-icon-voice"></text>
                </view>
                <view class="record-input" @touchstart="onRecordStart" @touchend="onRecordEnd" v-if="audio.visible" >{{audio.recording ? '松开发送' : '按住录音'}}</view>
                <view class="message-input" :style="content?'width: 60%;':'width: 65%;'" v-else>
                	<!-- GoEasyIM最大支持3k的文本消息，如需发送长文本，需调整输入框maxlength值 -->
                	<input style="width: 95%;" :disabled="no_speaking" type="text" maxlength="1000" placeholder="发送消息" v-model="content" @focus="messageInputFocusin">
                </view>
				<view :style="content?'width: 26%;':'width: 21%;'"  style="display: flex;align-items: center; ">
                    <view style="font-size: 31px;margin-bottom: 5rpx;" :class="emoji.visible?'n-icon-keyboard':'n-icon-face'" class="n-icon n-icon-face" @click="showEmoji"></view>
                    <view class="emoji" style="margin-left: 15rpx;" @click="showOtherTypesMessagePanel" v-if="!content">
                        <text style="font-size: 37px;color: #444; "> {{otherTypesMessagePanelVisible?'&#xe603;':'&#xe634;'}}</text>
                    </view>
                    <view class="btn sendbtn" v-if="content" @touchend.prevent="createTextMessage">发送</view>
                </view>
			</view>
            <!--展示表情列表-->
            <view class="action-bottom " v-if="emoji.visible">
                <scroller class="scroller">
                	<div append="tree" class="emoj_box" >
                		<block v-for="(item,index) in emojiList" :key="index">
                			<text @click="setEmoj(item,index)" class="emoj_box_img">{{item}}</text>
                		</block>
                	</div>
                </scroller>
            </view>
            <!-- 表情包图片 -->
            <view class="action-bottom " v-if="biaoFalse">
                <scroller class="scroller">
                	<div append="tree" class="emoj_box">
                		<block v-for="(item,index) in biaoList" :key="index">
                			<image @click="handleEmotionbiaoFalse(item)" style="margin: 5rpx; width: 110rpx;height: 110rpx;" :src="`https://de-a.nextapi.cc`+item"></image>
                		</block>
                	</div>
                </scroller>
            </view>
			<!--其他类型消息面板-->
			<view class="action-bottom" v-if="otherTypesMessagePanelVisible">
				<view class="more-item" @click="createImageMessage">
					<image style="width: 70rpx;height: 70rpx;" src="../../../static/aa/tu.png"></image>
					<text>图片</text>
				</view>
				<view class="more-item" @click="createVideoMessage">
					<image style="width: 70rpx;height: 70rpx;" src="../../../static/aa/pa.png"></image>
					<text>视频</text>
				</view>
				<view class="more-item" @click="biao">
					<image style="width: 70rpx;height: 70rpx;" src="../../../static/aa/bao.png"></image>
					<text>表情包</text>
				</view>
				<view class="more-item" @click="hongbao">
					<image style="width: 70rpx;height: 70rpx;" src="../../../static/aa/hh.png"></image>
					<text>发红包</text>
				</view>
				<view class="more-item" @click="shoucang">
					<image style="width: 70rpx;height: 70rpx;" src="../../../static/aa/cang.png"></image>
					<text>收藏</text>
				</view>
				<view class="more-item" style="padding-top: 10rpx;" @click="wen">
					<image style="width: 60rpx;height: 60rpx;" src="../../../static/aa/wen.png"></image>
					<text>文件</text>
				</view>
			</view>
		</view>
		<view class="action-popup" @touchmove.stop.prevent v-if="actionPopup.visible">
			<view class="layer"></view>
			<view class="action-box">
				<view class="action-item" @click="deleteSingleMessage">删除</view>
				<view class="action-item" v-if="actionPopup.recallable" @click="recallMessage">撤回</view>
				<view class="action-item" @click="showCheckBox">多选</view>
				<view class="action-item" @click="actionPopup.visible = false">取消</view>
			</view>
		</view>
		<view class="messageSelector-box" v-if="messageSelector.visible">
			<image class="messageSelector-btn" @click="deleteMultipleMessages" src="/static/images/delete.png"></image>
		</view>
        <redpick v-if="is_redpack_open" :item="redpack_info" @closePick="is_redpack_open=false;"
            @fresmsg="freshmsg_fromredopen"></redpick>
		<view class="record-loading" v-if="audio.recording"></view>
		<video v-if="videoPlayer.visible" :src="videoPlayer.url" id="videoPlayer" @fullscreenchange="onVideoFullScreenChange"></video>
	</view>
</template>

<script>
	import GoEasyAudioPlayer from '@/components/GoEasyAudioPlayer/GoEasyAudioPlayer';
	import EmojiDecoder from '../../../lib/EmojiDecoder';
	import restApi from '../../../lib/restapi';
    import emojix from '@/components/chat-list/bottom-input/minxi/emoji.js'
	const recorderManager = uni.getRecorderManager();
    import http from '@/library/http.js';
    import redpick from '@/components/get-redpick.vue'
    import api from "@/library/index.js"
    const GoEasy = uni.$GoEasy;
    const GRTC = uni.$GRTC;
	export default {
		name: 'groupChat',
		components : {
			GoEasyAudioPlayer,
            redpick
		},
		data () {
			// 定义表情
			
			return {
				//聊天文本框
				content: '',
				group:null,
				currentUser: uni.getStorageSync('userInfo'),
				//群成员
				groupMembers : {},
				//消息记录
				messages: [],
				//是否加载完所有历史消息
				allHistoryLoaded: false,
				//定义表情列表
				emoji : {
 					visible : false,
				},
				//是否展示‘其他消息类型面板’
				otherTypesMessagePanelVisible: false,
				audio : {
					startTime: null,
					//语音录音中
					recording : false,
					//录音按钮展示
					visible : false
				},
				videoPlayer : {
					visible : false,
					url : '',
					context : null
				},
				// 展示自定义消息框
				customMessageFormVisible: false,

				// 展示消息删除弹出框
				actionPopup:{
					visible: false,
					message: null,
					recallable: false,
				},
				// 消息选择
				messageSelector: {
					visible: false,
					messages: []
				},
                emojiList:[],
               text:'',
               biaoFalse:false,
               group:{},
               userid: uni.getStorageSync('access_token'),
               no_speaking:false,
               is_redpack_open:false
			}
		},
        computed: {
        	isType() {
        		return {
        			1: '手气红包',
        			2: '红包',
        			3: '专属红包',
        			4: '口令红包'
        		}
        	}
        },
        created() {
          this.emojiList = emojix  
        },
		onReady(){
			this.videoPlayer.context = uni.createVideoContext('videoPlayer',this);
			uni.setNavigationBarTitle({
				title : this.group.name + '（' + Object.keys(this.groupMembers).length + '）'
			});
		},
		onShow () {
			this.otherTypesMessagePanelVisible = false;
			this.emoji.visible = false;
             this.getuserinfodes()
             this.getInfo()
             this.initialGoEasyListeners();
             this.loadHistoryMessage(true);
             // 录音监听器
             this.initRecorderListeners();
		},
		onLoad(options) {
			//聊天对象
			let groupId = options.id;
            this.group = options;
            this.group.id = parseInt(this.group.id);
			//从服务器获取最新的群信息
           uni.setNavigationBarTitle({
               title: decodeURI(options.nickname)
           })
           this.getInfo()
            this.getGroupUsers()
			// 录音监听器
			this.initRecorderListeners();
           uni.$on('readpack',res => {
               if(res){
                   console.log('加载一次',res)
                   this.initialGoEasyListeners()
               }
           })
		},
		onPullDownRefresh(e) {
			this.loadHistoryMessage(false);
		},
        onNavigationBarButtonTap() {
            // this.$refs.panel.endVedio();
            this.$jump('group.detail', {
                id: this.group.id,
                'from': 'chat'
            });
        
        },
		onUnload() {
			//退出聊天页面之前，清空监听器
			this.goEasy.im.on(this.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, ()=>{});
			this.goEasy.im.on(this.GoEasy.IM_EVENT.MESSAGE_DELETED, ()=>{});
		},
        watch:{
           messages(val,old){
               console.log('大大大大爱国公司',val)
           } 
        },
		methods : {
           freshmsg_fromredopen(e){
               this.initialGoEasyListeners();
           },
            getuserinfodes() {
                var postdata = {
                    id: uni.getStorageSync('access_token')
                };
                http.setWait(false).post('user.php?act=userinfo', postdata).then(res => {
                    this.currentUser = res.data;
                    uni.setStorageSync('userInfo', this.currentUser)
                })
            
            },
            //发红包
            hongbao() {
            
                if (this.currentUser.banknum < 1) {
                    uni.showModal({
                        title: '提示',
                        // content: "绑定SK账号后才可以发送红包",
                        content: "绑定银行账号后才可以发送红包",
                        showCancel: true,
                        cancelText: '关闭',
                        confirmText: '立即绑定',
                        success: res => {
                            if (res.confirm) {
                                uni.navigateTo({
                                    url: "/pages/mine/bank"
                                })
                            }
                        }
                    });
                    return false;
                } else {
                    this.otherTypesMessagePanelVisible = false
                    uni.navigateTo({
                        url: '/pages/friend/readpacket?isgroup=1' + '&id=' + this.group.id+'&nickname='+this.group.nickname+'&avatar='+this.group.avatar
                    })
                }
            },
            // 表情
            biao(){
                this.biaoFalse = true
                this.emoji.visible = false
                this.otherTypesMessagePanelVisible = false
            },
            group_set(group) {
                this.group = group;
                if (group.deny_id == null) group.deny_id = '';
                if (group.manager_id == null) group.manager_id = '';
                if (this.currentUser.status == 1 || (this.currentUser.status == 2 && parseInt(this.currentUser.lock_time) >= Date.parse(
                        new Date()) / 1000)) {
                    this.no_speaking = true;
                    this.speaking_tips = '您的账号已被冻结';
                } else if ((group.no_speaking == 1) && !group.owner && group.manager_id.indexOf(this.userid) <= -1) {
                    this.no_speaking = true;
                    this.speaking_tips = '全体禁言,限群主和管理员可发消息';
                } else if ((group.deny_id.indexOf(this.userid) > -1) && !group.owner && group.manager_id.indexOf(this
                        .userid) <= -1) {
                    this.no_speaking = true;
                    this.speaking_tips = '您已被禁言';
                } else {
                    this.no_speaking = false;
                }
            
            
                if (group.manager_id.indexOf(this.userid) > -1 || group.owner) this.ismanage = true;
                else this.ismanage = false;
                if (group.is_owner == 1) var type = 'owner';
                else if (group.is_manager == 1) var type = 'manager';
                else var type = 'user';
                this.thistype = type;
            
            
                //    console.log(this.group);
                if ((group.no_add == 1) && this.ismanage == false)
                    this.no_add = true;
                else this.no_add = false;
            
                uni.setNavigationBarTitle({
                    title: `${group.name}(${group.people_count}人)`
                })
            
                uni.setStorageSync('group_' + group.id, group);
            },
            redpack_open(m){
                console.log('redpack_open',m)
                switch (m.payload.content.type) {
                	case '1':
                		this.getSendPay(m)
                		break;
                	case '2':
                		this.getSendPay(m)
                		break;
                	case '3':
                		this.getSendPay(m)
                		break;
                	case '4':
                		this.redkou_open(m)
                		break;
                
                }
            },
            // 口令红包
            redkou_open(m) {
            	uni.showModal({
            		title: '口令',
            		content: '',
            		editable: true, //是否显示输入框
            		placeholderText: '请输入口令', //输入框提示内容
            		confirmText: '确认',
            		cancelText: '取消',
            		success: (res) => {
            			if (res.confirm) {
            				console.log('输入的内容：', res.content,m);
            				if (!res.content) {
            					return uni.showToast({
            						title: '请输入口令',
            						icon: 'none'
            					})
            				}
            				if (m.payload.content.isopen != 0) {
            					uni.navigateTo({
            						url: '../friend/redpacket_detail?msg_id=' + m.msg_id +
            							'&storekey=' + m.cache_key + '&content=' + res.content
            					})
            				} else {
            					m.command = res.content
            					console.log('输入的内容：', m);
                                let dat = {
                                    sender:{
                                        nickname:this.currentUser.nickname,
                                        avatar:this.currentUser.avatar,
                                    },
                                    
                                    message:m.payload
                                }
                                this.kou_open(dat,res.content)
            					
            				}
            			}
            		}
            	})
            },
            kou_open(item,command){
                console.log('dadadadada',item,command)
            	this.redpack_info = item.message.content;
            	this.redpack_info.content = item.message.content
            	var postdata={userid:this.currentUser.id,id:item.message.content.id,command: command}
            
            	http.setWait(false).post('group.php?act=get_redpacket',postdata).then(res=>{
            	              
            	   if(res.code==200){
            	       // this.getover(res.data);
            		   uni.showToast({
            		   	title: '领取成功',
            			icon: 'none'
            		   })
            	   }
            	   else{
            	       clearInterval(this.timer)
            	        uni.showToast({
            	            title:'网络异常，请稍后再试',
            	            icon:'none'
            	        })
            	   }
            	
            	})
            },
            getSendPay(m) {
            	if (m.payload.content.isgroup != 0 && m.payload.content.type !=3 && m.payload.content.isopen == 1) {
            		uni.navigateTo({
            			url: '../friend/redpacket_detail?msg_id=' + m.friend_uid 
            		})
            	} else {
                    let dat = {
                        sender:{
                            nickname:this.currentUser.nickname,
                            avatar:this.currentUser.avatar,
                        },
                        message:m.payload
                    }
                    this.redpack_info = dat
            		this.is_redpack_open = true;
            	}
            },
            msgAction(e,m){
                console.log('点击领取红包',e,m) 
            },
            ceshi(order){
                let imageMessage = this.goEasy.im.createCustomMessage({
                	to : {
                		id : this.friend.id,
                		type : this.GoEasy.IM_SCENE.GROUP,
                		data : {
                			name:this.friend.nickname,
                			avatar:this.friend.avatar
                		}
                	},
                    type:'redpacket',
                    payload:order,
                	onProgress :function (progress) {
                		console.log(progress)
                	},
                	notification : {
                		title : this.currentUser.nickname + '发来一张表情',
                		body : '[表情]'		// 字段最长 50 字符
                	}
                });
                this.sendMessage(imageMessage);
            },
            // 点击选择表情图片
            handleEmotionbiaoFalse(item){
                console.log('点击选择表情图片',item)
                let imageMessage = this.goEasy.im.createCustomMessage({
                	to : {
                		id : this.friend.id,
                		type : this.GoEasy.IM_SCENE.GROUP,
                		data : {
                			name:this.friend.nickname,
                			avatar:this.friend.avatar
                		}
                	},
                    type:'emoji',
                    payload:`https://de-a.nextapi.cc${item}`,
                	onProgress :function (progress) {
                		console.log(progress)
                	},
                	notification : {
                		title : this.currentUser.nickname + '发来一张表情',
                		body : '[表情]'		// 字段最长 50 字符
                	}
                });
                this.sendMessage(imageMessage);
            },
            // 点击关闭
            dianji(){
                this.biaoFalse =false
                this.emoji.visible = false
                this.otherTypesMessagePanelVisible = false
            },
            setEmoj(item,index){
              this.content +=item  
            },
            // 左测消息，头像点击
            leftAvatarClick(item) {
            	console.log('左测消息，头像点击')
            	console.log(item)
                uni.navigateTo({
                    url:'/pages/friend/detail?id='+item
                })
            },
            group_init(id) {
                var group = uni.getStorageSync('group_' + id);
                if (group.id > 0 && group.id == id) this.group_set(group);
            },
            getInfo() {
                if (this.group.id > 0) {
                    this.group_init(this.group.id);
                    api.getGroupInfo({
                        group_id: this.group.id,
                        from_id: this.userid,
                    }).then(res => {
                        console.log('d阿达',res)
                        this.group_set(res.data);
                    })
                }
            },
            getGroupUsers() {
                api.getGroupUsers({
                    group_id: this.group.id,
                    userid: this.userid,
                }).then(res => {
                    console.log('获取群聊用户信讯',res.data)
                    uni.setStorageSync(this.group.id + '_group_members', res.data);
                })
            },
			//渲染文本消息，如果包含表情，替换为图片
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			renderTextMessage(message) {
				return '<span class="text-content">' + this.emoji.decoder.decode(message.payload.text) + '</span>';
			},
			//像微信那样显示时间，如果有几分钟没发消息了，才显示时间
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			renderMessageDate(message, index) {
				if (index === 0) {
					return this.formatDate(message.timestamp);
				} else {
					if (message.timestamp - this.messages[index - 1].timestamp > 5 * 60 * 1000) {
						return this.formatDate(message.timestamp);
					}
				}
				return '';
			},
			initialGoEasyListeners() {
				//监听群聊消息
				this.goEasy.im.on(this.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, (message) => {
					let groupId = message.groupId;
					if (groupId === this.group.id) {
						this.messages.push(message);
						//聊天时，收到消息标记为已读
						this.markGroupMessageAsRead(groupId);
						//收到新消息，是滚动到最底部
						this.scrollToBottom();
					}
				});
				//监听消息删除
				this.goEasy.im.on(this.GoEasy.IM_EVENT.MESSAGE_DELETED,(deletedMessages) => {
					deletedMessages.forEach(message => {
						let groupId = message.groupId;
						if (groupId && groupId === this.group.id) {
							let index = this.messages.indexOf(message);
							if (index > -1) {
								this.messages.splice(index, 1);
							}
						}
					});
				})
			},
			initRecorderListeners(){
				// 监听录音开始
				recorderManager.onStart(() => {
					this.audio.recording = true;
					this.audio.startTime = Date.now();
				});
				//录音结束后，发送
				recorderManager.onStop((res) => {
					let endTime = Date.now();
					this.audio.recording = false;
					let duration = endTime - this.audio.startTime;
					if (duration < 1000) {
						uni.showToast({
							icon: 'error',
							title: '录音时间太短',
							duration: 500
						});
						return;
					}
					res.duration = duration;
					let audioMessage = this.goEasy.im.createAudioMessage({
						to : {
							id : this.group.id,
							type : this.GoEasy.IM_SCENE.GROUP,
							data : 	{
								name : this.group.name,
								avatar : this.group.avatar
							}
						},
						file: res,
						onProgress :function (progress) {
							console.log(progress);
						},
						notification : {
							title : this.currentUser.name + '发来一段语音',
							body : '[语音消息]'		// 字段最长 50 字符
						}
					});
					this.sendMessage(audioMessage);
				});
				// 监听录音报错
				recorderManager.onError((res) =>{
					this.audio.recording = false;
					recorderManager.stop();
					uni.showToast({
						icon: 'none',
						title: '录音失败,请检查麦克风权限',
						duration: 1000
					});
				})
			},
			sendMessage(message){
				this.messages.push(message);
				this.scrollToBottom();
                let that = this
				this.goEasy.im.sendMessage({
					message: message,
					onSuccess: function (message) {
						console.log('发送成功.', message);
                       
					},
					onFailed: function (error) {
						if(error.code === 507){
							console.log('发送语音/图片/视频/文件失败，没有配置OSS存储，详情参考：https://docs.goeasy.io/2.x/im/message/media/alioss');
						}else{
							console.log('发送失败:',error);
						}
					}
				});
                let data = {
                    userid: message.senderId,
                    group_id: this.group.id,
                    type: 'group',
                    msgtype: message.type,
                    content: message.type == 'text'?message.payload.text:message,
                    mid: 'm' + Math.random().toString(36).substring(2)
                };
                that.$socket.send(data);
                this.goEasy.pubsub.publish({
                    channel: message.receiverId,  //请确认与接收端一致
                    message: message,
                    qos: 1,//app内onMessage收到的消息内容
                    notification: { //定义通知栏推送
                        title: '您有一条新消息', //通知栏提醒标题，仅显示于通知栏
                        body: message.payload.text, //通知栏提醒内容，仅显示于通知栏
                        badge: "+1", //角标，值必须有引号，"0"表示该消息不需要设置角标，"+1"表示角标+1，不支持其他值， 默认为“0”
                    },
                    onSuccess: function () {
                        console.log("推送消息时设置角标 successfully.")
                    },
                    onFailed: function (error) {
                        console.log("推送消息时设置角标 to publish message, code:" + error.code + ' error:' + error.content);
                    }
                });
			},
            getMSGlIST(user){
                let list = uni.getStorageSync('CallData')
                console.log('看看是否为空',list)
                if(list.length<=0){
                    
                } else {
                   list.forEach((item,index) => {
                       if(item.userId == user.groupId){
                           console.log('则不加缓存')
                           return 
                       } else {
                           list.push(user)
                           uni.setStorageSync('CallData',list)
                           console.log('否则加入缓存',uni.getStorageSync('CallData'))
                       }
                   })
                } 
            },
			createTextMessage () {
				if(this.content.trim() !== '') {
					let body = this.content;
					if(this.content.length >= 50){
						body = this.content.substring(0,30)+'...';
					}
					let textMessage = this.goEasy.im.createTextMessage({
						text:this.content,
						to : {
							id : this.group.id,
							type : this.GoEasy.IM_SCENE.GROUP,
							data : {
								name : this.group.name,
								avatar : this.group.avatar
							}
						},
						notification : {
							title : this.currentUser.name + '发来一段文字',
							body : body // 字段最长 50 字符
						}
					});
					this.sendMessage(textMessage);
				}
				this.content = '';
                this.videoPlayer.visible = false 
                this.messageSelector.visible = false
			},
			createVideoMessage () {
				uni.chooseVideo({
					success : (res) => {
						let videoMessage = this.goEasy.im.createVideoMessage({
							to : {
								id : this.group.id,
								type : this.GoEasy.IM_SCENE.GROUP,
								data : {
									name : this.group.name,
									avatar : this.group.avatar
								}
							},
							file: res,
							onProgress :function (progress) {
								console.log(progress)
							},
							notification : {
								title : this.currentUser.name + '发来一个视频',
								body : '[视频消息]'		// 字段最长 50 字符
							}
						});
						this.sendMessage(videoMessage);
					}
				})
			},
			createImageMessage() {
				uni.chooseImage({
					count : 9,
					success :(res) => {
						res.tempFiles.forEach(file => {
							let imageMessage = this.goEasy.im.createImageMessage({
								to : {
									id : this.group.id,
									type : this.GoEasy.IM_SCENE.GROUP,
									data : {
										name : this.group.name,
										avatar : this.group.avatar
									}
								},
								file: file,
								onProgress :function (progress) {
									console.log(progress)
								},
								notification : {
									title : this.currentUser.name + '发来一张图片',
									body : '[图片消息]'		// 字段最长 50 字符
								}
							});
							this.sendMessage(imageMessage);
						})
					}
				});
                
			},
			showActionPopup(message) {
				const MAX_RECALLABLE_TIME = 3 * 60 * 1000; //3分钟以内的消息才可以撤回
				this.messageSelector.messages = [message];
				if ((Date.now() - message.timestamp) < MAX_RECALLABLE_TIME && message.senderId === this.currentUser.id && message.status === 'success') {
					this.actionPopup.recallable = true;
				} else {
					this.actionPopup.recallable = false;
				}
				this.actionPopup.visible = true;
			},
			deleteSingleMessage(){
				uni.showModal({
					content: '确认删除？',
					success: (res) => {
							this.actionPopup.visible = false;
						if (res.confirm) {
							this.deleteMessage();
						}
					},
				})
			},
			deleteMultipleMessages(){
				if (this.messageSelector.messages.length > 0) {
					uni.showModal({
						content: '确认删除？',
						success: (res) => {
							this.messageSelector.visible = false;
							if (res.confirm) {
								this.deleteMessage();
							}
						},
					})
				}
			},
			deleteMessage() {
				this.goEasy.im.deleteMessage({
					messages: this.messageSelector.messages,
					onSuccess: (result)=>{
						this.messageSelector.messages.forEach(message => {
							let index = this.messages.indexOf(message);
							if (index > -1) {
								this.messages.splice(index, 1);
							}
						});
						this.messageSelector.messages = [];
					},
					onFailed: (error) => {
						console.log('error:', error);
					}
				});
			},
			recallMessage() {
				this.actionPopup.visible = false;
				this.goEasy.im.recallMessage({
					messages: this.messageSelector.messages,
					onSuccess: ()=>{
						console.log('撤回成功');
					},
					onFailed: (error) => {
						console.log('撤回失败,error:', error);
					}
				});
			},
			editRecalledMessage (content) {
				if (this.audio.visible) {
					this.audio.visible = false;
				}
				this.content = content;
			},
			showCheckBox () {
				this.messageSelector.messages = [];
				this.messageSelector.visible = true;
				this.actionPopup.visible = false;
			},
			selectMessages (e) {
				const selectedMessageIds = e.detail.value;
				let selectedMessages = [];
				this.messages.forEach(message => {
					if(selectedMessageIds.includes(message.messageId)){
						selectedMessages.push(message);
					}
				})
				this.messageSelector.messages = selectedMessages;
			},
			loadHistoryMessage (scrollToBottom) {//历史消息
				let lastMessageTimeStamp;
				let lastMessage = this.messages[0];
				if (lastMessage) {
					lastMessageTimeStamp = lastMessage.timestamp;
				}
				this.goEasy.im.history({
					groupId: this.group.id,
					lastTimestamp: lastMessageTimeStamp,
					limit: 10,
					onSuccess: (result) => {
						uni.stopPullDownRefresh();
						let messages = result.content;
						if (messages.length === 0) {
							this.allHistoryLoaded = true;
						} else {
							this.messages = messages.concat(this.messages);
							if (scrollToBottom) {
								this.scrollToBottom();
								//收到的消息设置为已读
								this.markGroupMessageAsRead(this.group.id);
							}
						}
					},
					onFailed: (error) => {
						//获取失败
						console.log('获取历史消息失败:',error);
						uni.stopPullDownRefresh();
					}
				});
			},
			showMembers () {//显示群成员
				uni.navigateTo({
					url : '../groupChat/member?users=' + JSON.stringify(this.groupMembers)
				});
			},
			onRecordStart () {
				try{
					recorderManager.start();
				}catch(e){
					uni.showModal({
						title: '录音错误',
						content : '请在app和小程序端体验录音，Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
					});
				}
			},
			onRecordEnd () {
				try{
					recorderManager.stop();
				}catch(e){
					console.log("e:",e);
				}
			},
			showImageFullScreen (e) {
				let imagesUrl = [e.currentTarget.dataset.url];
				uni.previewImage({
					urls: imagesUrl
				});
			},
			//语音录制按钮和键盘输入的切换
			switchAudioKeyboard() {
				this.audio.visible = !this.audio.visible;
				if(uni.authorize){
					uni.authorize({
						scope : 'scope.record',
						fail: () => {
							uni.showModal({
								title: '获取录音权限失败',
								content : '请先授权才能发送语音消息！'
							});
						}
					})
				}
			},
			playVideo (e) {
				this.videoPlayer.visible = true;
				this.videoPlayer.url = e.currentTarget.dataset.url;
				this.$nextTick(() => {
					this.videoPlayer.context.requestFullScreen({
						direction : 0
					});
					this.videoPlayer.context.play();
				});
			},
			onVideoFullScreenChange (e) {
				//当退出全屏播放时，隐藏播放器
				if(this.videoPlayer.visible && !e.detail.fullScreen){
					this.videoPlayer.visible = false;
					this.videoPlayer.context.stop();
				}
			},
			messageInputFocusin () {
				this.otherTypesMessagePanelVisible = false;
				this.emoji.visible = false;
			},
			showEmoji () {
				this.emoji.visible = !this.emoji.visible;
				this.otherTypesMessagePanelVisible = false;
                this.biaoFalse = false
			},
			showOtherTypesMessagePanel () {
				this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
				this.emoji.visible = false;
			},
			chooseEmoji (emojiKey) {
				this.content += emojiKey;
			},
			showCustomMessageForm () {
				this.customMessageFormVisible = true;
			},
			closeCustomMessageForm() {
				this.customMessageFormVisible = false;
			},
			scrollToBottom () {
				setTimeout(() => {
					uni.pageScrollTo({
						scrollTop: 2000000,
						duration: 0
					})
				},500);
			},
			markGroupMessageAsRead (groupId) {
				this.goEasy.im.markGroupMessageAsRead({
					groupId: groupId,
					onSuccess: function () {
						console.log('标记群聊已读成功');
					},
					onFailed: function (error) {
						console.log('标记群聊已读失败:',error);
					}
				})
			}
		}
	}
</script>

<style lang="scss">
    // @import "@/static/css/chat/style.scss";
    $redpackBgColor: #fa8d34;
    $control-height: 120upx;
    $input-height: $control-height - $uni-spacing-col-base * 2;
    .btn {
        line-height: $input-height - 10upx;
        height: $input-height - 10upx;
        color: #fff;
        text-align: center;
        background-color: #3388ff;
        
    }
    .sendbtn {

        margin-left: 10upx !important;
        padding: 0px 24upx !important;

    }
    .scroller {
        flex: 1;
    }
    
    .emoj_box {
        flex-direction: row;
        flex-wrap: wrap;
        justify-content: space-between;
    }
    
    .emoj_box_img {
        font-size: 50rpx;
        width: 83rpx;
        margin-right: 10rpx;
        height: 83rpx;
        text-align: center;
        line-height: 83rpx;
    }
    
    .redpack .info {
        display: table;
        table-layout: fixed;
        width: 100%;
        height: 60px;
        line-height: 60px;
    }
    
    .redpack .info view {
        display: table-cell;
        vertical-align: middle;
        padding: 0px 0px;
        margin: 0px 0px;
    }
    
    .redpack .info view.icon {
        width: 55px;
        text-align: center;
    }
    
    .redpack .info view.showtext {
        color: #fff;
        font-size: 16px;
        ;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    .redpack .info view.icon image {
        vertical-align: middle;
        width: 60rpx;
        height: 70rpx;
    }
    
    .redpack .title {
        height: 25px;
        line-height: 25px;
        color: #fff;
        font-size: 12px;
        border-top: #fa785e solid 1rpx;
    }
    
    .redpack.redpack-open .title {
        color: #fff;
        border-top: #ffd5ab solid 1px;
    }
    
    .redpack {
        background: rgb(246, 164, 81);
        color: #fff;
        border-radius: 8rpx;
    
        &:before {
            border-color: transparent $redpackBgColor transparent transparent;
        }
    
        &-open {
            background: #fbbc88;
            border-radius: 8rpx;
    
            .redpack-body-image {
                background: #fb5538;
            }
    
            .redpack-body-image::before {
                background: #FFF3E7;
                top: -110upx;
            }
    
            &:before {
                border-color: transparent #FDE1C3 transparent transparent;
            }
        }
    
        &-body {
            padding: 20upx;
            display: flex;
            align-items: center;
    
            &-image {
                background: #CD3D35;
                width: 70upx;
                height: 90upx;
                overflow: hidden;
                position: relative;
                border-radius: 6upx;
    
                &:before {
                    content: "";
                    display: block;
                    width: 140upx;
                    height: 140upx;
                    border-radius: 50%;
                    position: absolute;
                    top: -90upx;
                    left: 50%;
                    transform: translateX(-50%);
                    background: #FA5151;
                }
    
                &:after {
                    position: relative;
                    display: block;
                    content: '￥';
                    width: 28upx;
                    height: 28upx;
                    background-color: #f2523c;
                    color: #E08B34;
                    border-radius: 28upx;
                    line-height: 32upx;
                    font-size: 24upx;
                    transform: scale(.8);
                    margin: 36upx auto;
                    text-align: center;
                }
            }
    
            &-content {
                padding-left: 20upx;
    
            }
        }
    
        &-footer {
            font-size: 24upx;
            padding: 10upx 20upx;
            background: #fff;
            color: #999;
            border-bottom-left-radius: 12upx;
            border-bottom-right-radius: 12upx;
        }
    }
    
    .image:before {
        opacity: 0
    }
</style>
